package org.domain.demo.interceptor;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;

import org.domain.demo.entity.Users;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;


public class AuditTrailInterceptor extends EmptyInterceptor {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 560304275502421220L;
	
	
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		int userId = 0;
		if (getUser() != null) {
			userId = getUser().getUserId();
		}
		setValue(currentState, propertyNames, "userIdModified", userId);
		setValue(currentState, propertyNames, "dateModified", new Date());
		return true;
	}

	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		int userId = 0;
		if (getUser() != null) {
			userId = getUser().getUserId();
		}
		setValue(state, propertyNames, "userIdCreated", userId);
		setValue(state, propertyNames, "dateCreated", new Date());
		setValue(state, propertyNames, "userIdModified", userId);
		setValue(state, propertyNames, "dateModified", new Date());
		return true;
	}

	private void setValue(Object[] currentState, String[] propertyNames,
			String propertyToSet, Object value) {
		int index = Arrays.asList(propertyNames).indexOf(propertyToSet);
		if (index >= 0) {
			currentState[index] = value;
		}
	}
	
	public String onPrepareStatement(String sql) {
		return sql;
	}

	public Users getUser() {
		Users user = (Users)Component.getInstance("loggedInUser", ScopeType.SESSION);
		return user;
	}
	
}
